<template>
  <div class="create-or-edit">
    <el-form>
      <el-form-item label="资源名称">
        <el-input v-model="resource.name"></el-input>
      </el-form-item>
      <el-form-item label="资源路径">
        <el-input v-model="resource.url"></el-input>
      </el-form-item>
       <el-form-item label="资源分类">
          <el-select
            v-model="resource.categoryId"
            clearable
            placeholder="资源分类">
            <!-- 请求接口进行下拉菜单项设置 -->
            <el-option
              v-for="item in resourceCategories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
        <el-input
          v-model="resource.description"
          type="textarea"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="onCancel">取消</el-button>
        <el-button
          type="primary"
          @click="onSubmit"
        >确认</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// saveOrUpdate
import { getResourceCategories, getResourceById, saveOrUpdate } from '@/services/resource'
export default {
  name: 'CreateOrEdit',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    resourceId: {
      type: [Number, String]
    }
  },
  created () {
    if (this.isEdit) {
      this.loadResource()
    }
    // 加载资源列表
    this.loadResourceCategories()
  },
  data () {
    return {
      resource: {
        name: '',
        url: '',
        description: '',
        categoryId: 1
      },
      // resources: [],
      // 存储资源分类信息
      resourceCategories: []
    }
  },
  methods: {
    // 获取编辑资源ID信息
    async loadResource () {
      const { data } = await getResourceById(this.resourceId)
      // console.log(data)
      if (data.code === '000000') {
        this.resource = data.data
      }
    },
    onCancel () {
      // 设置取消状态，让父组件处理
      this.$emit('cancel')
      this.role = {}
    },
    // 保存或新增资源
    async onSubmit () {
      const { data } = await saveOrUpdate(this.resource)
      if (data.code === '000000') {
        // 关闭提示框（需要子组件向父组件传递状态）
        console.log(data)
        this.$emit('success')
        // 设置成功提示
        // if (this.isEdit) {
        //   this.$message.success('修改成功')
        // } else {
        //   this.$message.success('添加成功')
        // }
        console.log(data)
        this.$message.success(`${this.isEdit === true ? '修改' : '添加'}成功`)
        // 清除表单内容
        this.resource = {}
      }
    },
    // 加载资源列表
    async loadResourceCategories () {
      const { data } = await getResourceCategories()
      if (data.code === '000000') {
        this.resourceCategories = data.data
      }
    }
  }
}
</script>

<style>

</style>
